package com.fw.service.persistence.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;

import com.fw.service.persistence.ParentMerchantPersistenceService;
import com.fw.service.persistence.dao.ParentMerchantDAO;
import com.fw.service.persistence.dto.ParentMerchant;

/**
 * 
 * @author AS073
 *
 */
public class ParentMerchantPersistenceServiceImpl implements ParentMerchantPersistenceService {

    @Autowired
    private ParentMerchantDAO parentMerchantDAO;

    @Override
    public List<ParentMerchant> selectByParentIdAndStatus(final String parentId, final String parentStatus) {
	Specification<ParentMerchant> specification = new Specification<ParentMerchant>() {
	    @Override
	    public Predicate toPredicate(Root<ParentMerchant> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
		List<Predicate> predicates = new ArrayList<Predicate>();
		if (parentId != null && !parentId.isEmpty()) {
		    predicates.add(cb.like(root.<String> get("parentId"), parentId));
		}
		if (parentStatus != null && !parentStatus.isEmpty()) {
		    predicates.add(cb.equal(root.<String> get("parentStatus"), parentStatus));
		}
		Predicate result = cb.conjunction();
		for (Predicate predicate : predicates) {
		    result.getExpressions().add(predicate);
		}
		return result;
	    }
	};
	return parentMerchantDAO.findAll(specification);
    }

    @Override
    public ParentMerchant save(ParentMerchant parentMerchant) {
	return parentMerchant == null ? null : parentMerchantDAO.save(parentMerchant);
    }

    @Override
    public ParentMerchant findOne(Long id) {
	return id == null ? null : parentMerchantDAO.findOne(id);
    }

    @Override
    public Page<ParentMerchant> findAll(Specification<ParentMerchant> specification, PageRequest pageRequest) {
	return specification == null || pageRequest == null ? null : parentMerchantDAO.findAll(specification, pageRequest);
    }

}
